package com.situ.allaia.controller;

import com.situ.allaia.common.Global;
import com.situ.allaia.model.*;
import com.situ.allaia.service.CartService;
import com.situ.allaia.service.OrderService;
import com.situ.allaia.service.UserAddressService;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/order")
public class OrderController {
    private final OrderService orderService;
    private final UserAddressService userAddressService;
    private final CartService cartService;


    public OrderController(OrderService orderService, UserAddressService userAddressService, CartService cartService) {
        this.orderService = orderService;
        this.userAddressService = userAddressService;
        this.cartService = cartService;
    }

    //创建订单
    @GetMapping("/add")
    public String add(HttpSession session, Map<String, Object> map) {
        User user = Global.findUser(session);
        //创建订单，创建订单项
        Order order = new Order();
        order.setUser(user);
        order.setShipping(BigDecimal.valueOf(15));//快递费用
        order.setState("未支付");
        order.setPayType("微信支付");//支付方式

        //保存，创建订单
        order = orderService.save(order);

        //放到请求域中
        map.put("order", order);

        //列出所有用户地址
        List<UserAddress> addresses = userAddressService.findByUserId(user.getId());
        map.put("addresses", addresses);

        return "order";
    }

    //修改订单地址
    @PatchMapping(value = "patch", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> patch(Order order) {
        boolean success = orderService.patch(order);
        System.out.println(order);
        return Map.of("success", success);
    }

    @GetMapping(value = "/items", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> findOrderItems(Long id) {
        Order order = orderService.findById(id);
        List<OrderItem> items = order.getItems();

        return Map.of("success", true, "data", items);
    }

    /**
     * 确认收货
     */
    @PatchMapping(value = "/confirm", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> confirm(Long id) {
        Order order = orderService.findById(id);
        if (order.getState().equals("已发货")) {
            order.setState("已确认");
            boolean b = orderService.patch(order);
            return Map.of("success", b);
        } else {
            return Map.of("success", false, "error", "只有已发货才以有确认收货");
        }
    }
}
